import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:taonile/config/config.dart';
import 'package:tobias/tobias.dart';

import '../entity/pay_methods_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';

///
/// 收银台
///
class OrderCashier extends StatefulWidget {
  var amount = '0';
  var orderNo = '';
  var skuId = '';
  var payApiType = '1'; //支付接口，目前有两种，1就代表老的，2就是新的

  OrderCashier(
      {Key? key, this.amount = '0', this.orderNo = '', this.skuId = '', this.payApiType = '1'})
      : super(key: key);

  @override
  State<OrderCashier> createState() => _OrderCashierState();
}

class _OrderCashierState extends State<OrderCashier> {
  List<PayMethodsData> datas = [];

  int currentIndex = 0;
  String payPwd = '';
  double payItemHight = 100.w;

  // var pay_pwd_exists = '1';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPayMethods();
  }

  getPayMethods() async {
    EasyLoading.show(status: 'loading...');
    dynamic result = await Api.payMethods(widget.orderNo);
    setState(() {
      datas = PayMethodsEntity.fromJson(result).data;
    });
    EasyLoading.dismiss();
  }

  checkPayPwd() async {
    dynamic result = await Api.checkSetPayPwd();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String pay_pwd_exists = jsonResult['data']['pay_pwd_exists'];
      return pay_pwd_exists;
    }
    return "0";
  }

  orederPay() async {
    FocusManager.instance.primaryFocus?.unfocus();

    var content = const Utf8Encoder().convert(payPwd);
    String md5pwd = "${md5.convert(content)}";
    dynamic result;
    if (widget.payApiType == '1') {
      result = await Api.orderPay({
        "order_no": widget.orderNo,
        "pay_pwd": md5pwd,
        "pay_channel": datas[currentIndex].payChannel.toString(),
      });
    } else {
      result = await Api.orderPayNew({
        "order_no": widget.orderNo,
        "pay_pwd": md5pwd,
        "pay_channel": datas[currentIndex].payChannel.toString(),
      });
    }
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("支付成功");
      Routes.router.pop(context, {'result': 1});
    }
  }

  //支付前判断渠道
  payConfrim() async {
    if (datas[currentIndex].payChannel == '6') {
      //支付宝渠道,先获取支付参数，然后调用支付宝
      var result = await isAliPayInstalled();
      if (!result) {
        EasyLoading.showToast('未安装支付宝客户端');
      } else {
        // EasyLoading.showToast('可以调支付宝了');
        aliPayStart();
      }
    } else {
      //内部渠道,输入密码即可
      String isCheck = await checkPayPwd();
      if (isCheck == '1') {
        //付款弹出
        _showDialogForPinInput(context);
      } else {
        //请用户去设置支付密码
        DialogManager.showDefaultDialog(context, "你还未设置支付密码，请前往设置", () async {
          Routes.navigateTo(context, Routes.mineChangePassword, params: {'pageTitle': '修改支付密码'});
        });
      }
    }
  }

  aliPayStart() async {
    dynamic result = await Api.orderPay({
      "order_no": widget.orderNo,
      "pay_channel": datas[currentIndex].payChannel.toString(),
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    String param = jsonResult['data']['response_usd_price'];

    // LogUtil.v(param, tag: 'alipay支付参数=');
    aliPay(param).then((payResult) {
      LogUtil.v(payResult, tag: 'alipay支付结果=');
      if (payResult['resultStatus'] == '9000') {
        EasyLoading.showToast("支付成功");
        Routes.router.pop(context, {'result': 1});
      } else {
        EasyLoading.showToast("支付失败${payResult['resultStatus']}");
      }
    });
  }

  Widget getListItem(int index) {
    return InkWell(
      onTap: () {
        setState(() {
          currentIndex = index;
        });
      },
      child: Container(
        height: 100.w,
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 0.w, horizontal: 20.w),
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 3.w, color: Config.colorDivider)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              children: [
                Container(
                  width: 55.w,
                  height: 55.w,
                  color: (Config.colorWhite),
                  padding: EdgeInsets.all(3.w),
                  child: CachedNetworkImage(
                    imageUrl: datas[index].icon,
                    fit: BoxFit.fill,
                    width: 55.w,
                    height: 55.w,
                    errorWidget: (context, url, error) {
                      return Image.asset(
                        'assets/images/bg_default_400.png',
                        width: 55.w,
                        height: 55.w,
                        fit: BoxFit.fill,
                      );
                    },
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 17.w),
                ),
                Text(
                  datas[index].pay.isNotEmpty
                      ? '${datas[index].payName}(${datas[index].pay})'
                      : datas[index].payName,
                  style: TextStyle(
                    fontSize: 26.w,
                    color: Config.colorText1,
                  ),
                ),
              ],
            ),
            Opacity(
              //这个当作占位隐藏，不占位隐藏用Visibility
              opacity: currentIndex == index ? 1 : 0,
              child: Icon(
                Icons.check_circle_outline_outlined,
                size: 46.w,
                color: Config.colorMain,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _showDialogForPinInput(context) {
    payPwd = '';
    AwesomeDialog(
      context: context,
      animType: AnimType.SCALE,
      dialogType: DialogType.NO_HEADER,
      body: Container(
        padding: EdgeInsets.only(top: 5.w, left: 20.w, right: 20.w),
        child: Column(
          children: [
            Text(
              "请输入支付密码",
              style: TextStyle(color: Config.colorText1, fontSize: 30.sp),
            ),
            Padding(
              padding: EdgeInsets.only(top: 30.w),
            ),
            PinCodeTextField(
              appContext: context,
              length: 6,
              obscureText: true,
              // controller: textEditingController,
              onChanged: (value) {},
              keyboardType: TextInputType.phone,
              onCompleted: (value) {
                payPwd = value;
              },
              // pinTheme: PinTheme(
              //   shape: PinCodeFieldShape.box, //输入框的形状
              //   borderRadius: const BorderRadius.all(Radius.circular(10)),
              //   // 其他可以设置可以自己参考，比如有输入文字的时候输入框是什么颜色，不能输入的时候是什么颜色等
              // ),
            ),
            InkWell(
              onTap: () {
                Routes.navigateTo(context, Routes.mineChangePassword,
                    params: {'pageTitle': '修改支付密码'});
              },
              child: Container(
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 2.w),
                child: Text(
                  "忘记密码?",
                  style: TextStyle(
                      color: Config.colorText1,
                      fontSize: 25.sp,
                      decoration: TextDecoration.underline),
                ),
              ),
            ),
          ],
        ),
      ),
      title: '',
      desc: '',
      btnOkText: '确定',
      btnOkColor: Config.colorMain,
      btnOkOnPress: () {
        // print('oncompletd $payPwd');
        if (payPwd.isEmpty) {
          return;
        }
        orederPay();
      },
    ).show();
  }

  Future<bool> _onWillPop() {
    Routes.router.pop(context, {'result': 0});
    return Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          backgroundColor: Config.colorBg2,
          appBar: AppBar(
            title: const Text('收银台'),
            centerTitle: true,
            leading: IconButton(
                onPressed: () {
                  Routes.router.pop(context, {'result': 0});
                },
                icon: const Icon(Icons.arrow_back)),
          ),
          body: Container(
            width: double.infinity,
            height: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    height: 100.w,
                    padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 20.w),
                    margin: EdgeInsets.fromLTRB(30.w, 30.w, 30.w, 0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "支付金额",
                          style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 5.w),
                        ),
                        Text(
                          widget.amount,
                          style: TextStyle(fontSize: 26.sp, color: Colors.redAccent),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    margin: EdgeInsets.only(top: 35.w, left: 30.w, right: 30.w),
                    child: Text(
                      "请选择支付方式",
                      style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: payItemHight * datas.length,
                    margin: EdgeInsets.symmetric(vertical: 30.w, horizontal: 30.w),
                    decoration: BoxDecoration(
                      color: (Config.colorWhite),
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    child: ListView.builder(
                      itemCount: datas.length,
                      scrollDirection: Axis.vertical,
                      itemBuilder: (BuildContext context, int index) {
                        return getListItem(index);
                      },
                    ),
                  ),
                  Container(
                    width: 670.w,
                    height: 84.w,
                    margin: EdgeInsets.fromLTRB(35.w, 35.w, 35.w, 0),
                    child: ElevatedButton(
                      clipBehavior: Clip.antiAlias,
                      onPressed: () async {
                        payConfrim();
                      },
                      style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                      child: const Text('确认付款'),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ));
  }
}
